package com.sinog.front.controller.biz.common;

import com.sinog.core.model.UploadAppendixFile;
import com.sinog.core.util.CollectionUtils;
import com.sinog.core.utilbean.Constants;
import com.sinog.front.feign.biz.FtpUtilService;
import com.sinog.front.feign.biz.ZcwjService;
import com.sinog.front.service.azbj.uploadappendix.UploadAppendixFileService;
import com.sinog.front.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @desc 公用下载删除附件表控制器
 * @author lzq
 * @date 2022/4/16 18:34
 */
@Slf4j
@RestController
public class CommonDownloadController {

    private static final Pattern COMPILE = Pattern.compile("@@@@@",Pattern.LITERAL);
    @Autowired
    private FtpUtilService ftpUtilService;
    @Value("${gkzx.azbj.uploadfilepath.windows}")
    String uploadPath;
    @Value("${gkzx.azbj.uploadfilepath.unix}")
    String linuxUploadPath;
    @Resource
    private ZcwjService zcwjService;
    @Resource
    private UploadAppendixFileService uploadAppendixFileService;

    /**
     * 政策文件/经验推介下载附件
     * @param resp resp
     * @param request request
     * @param id id
     * @param taskId taskId
     */
    @RequestMapping("/azbj/abzlxxgl/zcwjInfoManage/downloadFilesZip")
    public void downloadFilesZip(HttpServletResponse resp,HttpServletRequest request,String id,String taskId) {
        Map<String,Object> map = new HashMap<>(16);
        map.put("id",id);
        map.put("taskId",taskId);
        //根据列表id查询附件list数据
        List<UploadAppendixFile> uploadAppendixFiles = zcwjService.getFilesListdata(map);
        if(CollectionUtils.isNotEmpty(uploadAppendixFiles)) {
            if(Constants.Number.NUM_ONE < uploadAppendixFiles.size()) {
                uploadAppendixFileService.downloadAppendixAllFile(resp,request,uploadAppendixFiles,Constants.NumberStr.NUM_STR_ONE);
            } else {
                uploadAppendixFileService.downloadAppendixFile(request,resp,uploadAppendixFiles.get(Constants.Number.NUM_ZERO)
                                                                                               .getFileUrl(),Constants.NumberStr.NUM_STR_ONE);
            }
            return;
        }
        //查询部级系统附件List数据
        List<UploadAppendixFile> bjFilesListdata = zcwjService.getBjFilesListData(map);
        //下载部级附件
        if(CollectionUtils.isNotEmpty(bjFilesListdata)) {
            if(Constants.Number.NUM_ONE < bjFilesListdata.size()) {
                uploadAppendixFileService.downloadAppendixAllFile(resp,request,bjFilesListdata,Constants.NumberStr.NUM_STR_TWO);
            } else {
                uploadAppendixFileService.downloadAppendixFileSingle(request,resp,bjFilesListdata.get(Constants.Number.NUM_ZERO),Constants.NumberStr.NUM_STR_TWO);
            }
        }
    }

    /**
     * 删除附件表
     * @param map map
     * @return boolean
     */
    public boolean deleteFjInfo(Map<String,Object> map) {
        boolean result = false;
        //存在附件，删除附件表信息
        boolean fjinforesult = true;
        List<UploadAppendixFile> uploadAppendixFiles = zcwjService.getFilesListdata(map);
        if(!uploadAppendixFiles.isEmpty()) {
            //删除附件表
            int fjdelete = zcwjService.deleteFjByid(map);
            if(uploadAppendixFiles.size() != fjdelete) {
                fjinforesult = false;
            }
        }
        //存在附件，删除附件文件
        boolean deletefileResult = true;
        if(!uploadAppendixFiles.isEmpty()) {
            for(UploadAppendixFile uploadAppendixFile : uploadAppendixFiles) {
                String path = FileUtil.getUploadFilePath();
                File file = new File(path + uploadAppendixFile.getFileUrl());
                if(file.exists()) {
                    deletefileResult = file.delete();
                }
            }
        }
        if(fjinforesult && deletefileResult) {
            result = true;
        }
        return result;
    }

    /**
     * 安置帮教管理 - 帮教对象信息管理 - 户籍迁出人员管理 - 迁移办理 - 读取图片
     * @param request request
     * @param response response
     */
    @ResponseBody
    @RequestMapping("/azbj/bjdxInfo/hjqc/toViewTabs/view/readPartImage")
    public void readPartImage(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String path = request.getParameter("url");
        path = COMPILE.matcher(path).replaceAll(Matcher.quoteReplacement("\\"));
        String operaOs = System.getProperty("os.name");
        String filepath = uploadPath;
        if(!operaOs.toLowerCase().startsWith(Constants.StrFinalValue.WIN)) {
            filepath = linuxUploadPath;
        }
        String realPath = filepath + path;
        File file = new File(realPath);
        if(!file.exists()) {
            //如果本地不存在，则去ftp服务器下载到服务器本地
            ftpUtilService.downLoadFromFtp(realPath,filepath);
            file = new File(realPath);
            if(!file.exists()) {
                return;
            }
        }
        InputStream is = null;
        OutputStream oss = null;
        try {
            is = new FileInputStream(file);
            byte[] bytes = new byte[is.available()];
            is.read(bytes);
            oss = response.getOutputStream();
            String fileSuffix = path.substring(path.lastIndexOf('.') + 1);
            if(Constants.ImageType.IMAGE_PNG.equals(fileSuffix)) {
                response.setContentType("image/png");
            }
            if(Constants.ImageType.IMAGE_JPG.equals(fileSuffix) || Constants.ImageType.IMAGE_JPEG.equals(fileSuffix)) {
                response.setContentType("image/jpeg");
            }
            if(Constants.ImageType.IMAGE_BMP.equals(fileSuffix)) {
                response.setContentType("image/bmp");
            }
            oss.write(bytes);
        } catch(FileNotFoundException e) {
            log.error("发生异常:",e);
        } finally {
            if(null != is) {
                is.close();
            }
            if(null != oss) {
                oss.close();
            }
        }
    }
}